package com.cloudm.technician.ui.modules.common.splash

import com.cloudm.technician.data.preferences.PreferencesHelper
import com.cloudm.technician.extensions.logger
import com.cloudm.technician.ui.base.RxPresenter
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * 作者: wesley
 * 时间: 2017/12/13
 * 描述: 闪屏页的业务逻辑
 */
class SplashPresenter(private val view: SplashContract.View,
                      private val preferencesHelper: PreferencesHelper) : RxPresenter(),
        SplashContract.Presenter {


    override fun openActivity(delay: Long) {
        if (checkIsFirstTimeIn()) {
            openActivityDelay(0, delay)
            return
        }

        if (!checkIsLogin()) {
            openActivityDelay(1, delay)
            return
        }

        openActivityDelay(2, delay)
    }

    override fun checkIsFirstTimeIn(): Boolean = preferencesHelper.isFirstTimeIn

    override fun checkIsLogin(): Boolean = preferencesHelper.isLogin

    override fun openActivityDelay(flag: Int, delay: Long) {
        Observable.timer(delay, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io()).observeOn(
                AndroidSchedulers.mainThread()).filter { view.isActive }.subscribe {
            when (flag) {
                0 -> view.openGuideActivity()
                1 -> view.openLoginActivity()
                2 -> view.openHomeActivity()
                else -> logger(" SplashPresenter openActivityDelay...")
            }
        }
    }
}